// /src/mock/index.js
import * as M from './data'

// 给未导出的数据兜底
const {
	mockRunRecordsByMonth = {},
		mockCourses = [],
		mockNewsToday = [],
		mockTodaySteps = 5678
} = M

// —— 工具：解析 query（兼容相对/绝对）—— //
function getQuery(url = '') {
	try {
		const u = url.startsWith('http') ? url : `https://mock.local${url}`
		const sp = new URL(u).searchParams
		const obj = {}
		for (const [k, v] of sp.entries()) obj[k] = v
		return obj
	} catch {
		return {}
	}
}

// —— 工具：提取 pathname（兼容相对/绝对）—— //
function getPathname(url = '') {
	try {
		return url.startsWith('http') ?
			new URL(url).pathname :
			new URL(`https://mock.local${url}`).pathname
	} catch {
		return url || ''
	}
}

// —— 统一响应：以“回调方式”驱动 http/request.js —— //
function respond(options, data, statusCode = 200, delay = 250) {
	const res = {
		statusCode,
		data,
		errMsg: 'request:ok',
		header: {},
		cookies: []
	}
	const timer = setTimeout(() => {
		try {
			options.success && options.success(res)
		} catch (e) {}
		try {
			options.complete && options.complete(res)
		} catch (e) {}
	}, delay)
	// 模拟 RequestTask
	return {
		abort() {
			clearTimeout(timer)
		}
	}
}

export function setupMock({
	enable = true,
	delay = 250
} = {}) {
	if (!enable) return

	// 幂等：已打过补丁直接返回
	if (uni.request && uni.request.__isMockPatched) return

	const original = uni.request

	const patched = function mockRequest(options = {}) {
		const method = (options.method || 'GET').toUpperCase()
		const url = options.url || ''
		const data = options.data || {}

		const pathname = getPathname(url)
		const q = {
			...getQuery(url),
			...data
		}

		// —— 跑步记录：GET /api/run/records?month=YYYY-MM —— //
		if (method === 'GET' && /^\/api\/run\/records$/.test(pathname)) {
			const list = mockRunRecordsByMonth[q.month] || []
			return respond(options, {
				list
			}, 200, delay)
		}

		// —— 课程：GET /api/courses —— //
		if (method === 'GET' && /^\/api\/courses$/.test(pathname)) {
			return respond(options, {
				list: mockCourses
			}, 200, delay)
		}

		// —— 今日步数：GET /api/steps/today —— //
		if (method === 'GET' && /^\/api\/steps\/today$/.test(pathname)) {
			return respond(options, {
				steps: Number(mockTodaySteps)
			}, 200, delay)
		}

		// —— 今日新闻：GET /api/news 或 /api/news/today —— //
		// /api/news or /api/news/today （分页）
		if (method === 'GET' && /^\/api\/news(\/today)?$/.test(pathname)) {
			const page = Math.max(1, parseInt(q.page || 1))
			const pageSize = Math.max(1, parseInt(q.pageSize || 10))
			const start = (page - 1) * pageSize
			const end = start + pageSize
			const full = mockNewsToday || []
			const slice = full.slice(start, end)
			const hasMore = end < full.length
			return respond(options, {
				list: slice,
				hasMore,
				page,
				pageSize,
				total: full.length
			}, 200, delay)
		}


		// 其它走真实请求
		return original.call(uni, options)
	}

	// 打标记，便于外部判断
	patched.__isMockPatched = true
	uni.request = patched

	console.info('[mock] uni.request patched')
}